package com.sdd.rpi_mobile.eventRss;

import java.net.URL;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.sdd.rpi_mobile.R;
import com.sdd.rpi_mobile.homeScreen.GridChooser;

/** Shows the contents of an RSS feed formatted as a list */
public class RssFeedActivity extends Activity {
	
	private List<String> mRssItemTitles;
	private ListView mListview;

	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list_view_loader);
		
		// Enable the Home button in the action bar.
		if (Build.VERSION.SDK_INT >= 14){
			getActionBar().setHomeButtonEnabled(true);
		}
				
		mListview = (ListView) findViewById(R.id.list_view);
		List<RssItem> rssItems = null;
		
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		
		if(networkInfo != null && networkInfo.isConnected()) {
			Bundle bundle = this.getIntent().getExtras();
			URL url = (URL) bundle.getSerializable("rss_url");
			AsyncTask<String, Void, List<RssItem>> rssGet = new FeedDisplay().execute(url.toString());
			try {
				rssItems = rssGet.get();
				if(rssItems == null) throw new NullPointerException();
				mRssItemTitles = new ArrayList<String>();
				DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT);
				for(RssItem item: rssItems) {
					String title = item.getTitle();
					if(title.length() > 35) {
						title = title.substring(0,35) + "...";
					}
					Date publicationDate = item.getPubDate();
					if(publicationDate != null){
						mRssItemTitles.add(title + " " + df.format(item.getPubDate()));
					}
					else{
						mRssItemTitles.add(title);
					}
				}
				if(mRssItemTitles.size() == 0) throw new NullPointerException();
				mListview.setAdapter(new ArrayAdapter<String>(this, 
						android.R.layout.simple_list_item_1, mRssItemTitles));
			} catch (InterruptedException e) {
				sendError();
				return;
			} catch (ExecutionException e) {
				sendError();
				return;
			} catch (NullPointerException e) {
				sendError();
				return;
			}
		}
		
		final List<RssItem> fRssItems = rssItems;
		mListview.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int pos,long id) {
				Bundle bundle = new Bundle();
				bundle.putSerializable("rss_item", fRssItems.get(pos));
				Intent intent = new Intent(view.getContext(), RSSItemActivity.class);
				intent.putExtra("rss_bundle", bundle);
				startActivity(intent);
			}
			
		});
	}

	/** Shows a list notifying the user that the schedule could not be retrieved*/
	private void sendError()
	{
		mRssItemTitles = new ArrayList<String>();
		mRssItemTitles.add("Unable to retrieve schedule");
		mListview.setAdapter(new ArrayAdapter<String>(this, 
				android.R.layout.simple_list_item_1, mRssItemTitles));
		return;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.rss_item_list, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case android.R.id.home:
	            // app icon in action bar clicked; go home
	            Intent intent = new Intent(this, GridChooser.class);
	            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	            startActivity(intent);
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
}
